package com.atgm.common.utils;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT token 工具类
 */
@Slf4j
@Component
public class JwtUtils {

    //密钥
    private static String JWT_SECERT = "gmmall2021pdx";

    //失效时间
    private static Long expiration = 1 * 24 * 60 * 60 * 1000L;  //1天

    //签发人
    private static String ISS = "pdx";

    public static SecretKey generateKey() {

        try {
            byte[] bytes = JWT_SECERT.getBytes("UTF-8");
            SecretKey aes = new SecretKeySpec(bytes, 0, bytes.length, "AES");
            return aes;
        }catch (Exception e) {
            log.error("生成密钥失败");
        }
        return null;
    }

    /**
     * 根据用户名、id 生成token
     * @param id
     * @param username
     * @return
     */
    public static String generateToken(Long id, String username) {
        //时间、现在
        long now = System.currentTimeMillis();
        //用户信息
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("username", username);
        JwtBuilder builder = Jwts.builder()
                //算法、秘钥
                .signWith(SignatureAlgorithm.HS512, generateKey())
                //token生成时间
                .setIssuedAt(new Date(now))
                //过期时间
                .setExpiration(new Date(now + expiration))
                //token中信息
                .setClaims(claims)
                //签发人
                .setIssuer(ISS);
        return builder.compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseJWT(String token) {
        return Jwts.parser()
                .setSigningKey(generateKey())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 验证token信息
     * @param token
     * @return
     */
    public static boolean validateJWT(String token) {
        Claims claims = null;
        try {
            claims = parseJWT(token);
            return true;
        } catch (ExpiredJwtException e) {
            log.error("token信息过期");
            return false;
        } catch (Exception e) {
            log.error("token信息验证失败");
            return false;
        }
    }

    /**
     * 获取登录用户的id
     * @param token
     * @return
     */
    public static Long getMemberId(String token) {
        Claims claims = parseJWT(token);
        Long memberId = (Long) claims.get("id");
        return memberId;
    }

    /**
     * 获取登录用户的用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        Claims claims = parseJWT(token);
        String username = (String) claims.get("username");
        return username;
    }

}
